package com.jacky.iot;

import com.alibaba.fastjson.JSONObject;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

public class MqttClientApp {

    private static final String MQTT_BROKER = "tcp://127.0.0.1:1883";
    private static final String clientId = "thmq-jhQFiJE"; // 设备TOKEN
    private static final String username = "devTest"; // 设备TOKEN
    private static final Random rand = new Random(12); // 固定随机种子保证可重复

    public static void main(String[] args) throws InterruptedException, MqttException {
//        ClientCallback callback = new ClientCallback();
//        ConnectionManager manager = new ConnectionManager();
//        MqttClient client = manager.initClient(MQTT_BROKER, clientId, username, null, callback);
//
//        TimeUnit.MINUTES.sleep(2);
//        MqttMessage msg = new MqttMessage();
//        msg.setPayload("msg from thmq-jhQFiJE".getBytes(StandardCharsets.UTF_8));
//        msg.setId(12564);
//        msg.setQos(2);
//        client.publish("tbmq/dev001/up/data",msg);
//        MqttClientApp app = new MqttClientApp();
////        app.mockGPSInfo(client);
//        TimeUnit.MINUTES.sleep(2);
    }

    private void mockGPSInfo(MqttClient client) {
        AtomicReference<Double> baseLng = new AtomicReference<>(113.934086);
        AtomicReference<Double> baseLat = new AtomicReference<>(22.540000);
        AtomicReference<Double> speed = new AtomicReference<>(50.0);
        boolean isStopped = true;
        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
        ScheduledFuture<?> future = executor.scheduleWithFixedDelay(() -> {

            // 速度变化（带惯性）
            double acceleration = rand.nextDouble() * 8 - 3; // [-3,5)
            speed.set(Math.max(0, Math.max(40, speed.get() + acceleration)));

            // 计算位置变化
            double lngDelta = (speed.get() / 3.6) * 5 * 0.0000111;
            double latDelta = (rand.nextDouble() * 0.000002) - 0.000001;

            // 更新状态
            Double lng = baseLng.updateAndGet(v -> v + lngDelta);
            Double lat = baseLat.updateAndGet(v -> v + latDelta);

            System.out.println("lng:" + lng + ",lat:" + lat + ",speed:" + speed.get());

            try {
                HashMap<String, Double> info = new HashMap<>();
                info.put("lon", lng);
                info.put("lat", lat);
                info.put("Speed", speed.get());
                String jsonInfo = JSONObject.toJSONString(info);
                client.publish("v1/devices/me/telemetry", new MqttMessage(jsonInfo.getBytes(StandardCharsets.UTF_8)));
            } catch (Exception e) {
                System.out.println("push error:" + e.getMessage());
            }
        }, 1, 5, TimeUnit.SECONDS);
    }


}